
//Module definition
var PACKAGE = PACKAGE || (function () {
    return {};
}());

PACKAGE.panel = (function(PACKAGE,$){
    /**
     * Function to update the search panel data, with updated facet counts.
     */
    var updateSearchPanel=function(autoRefresh,object) {
        if ($('#refreshSearchPanel').length > 0) {
            var pURL = "/ota/" + $('#refreshSearchPanel').val() + "searchresult";
            //In this case is in order to refresh the search panel in a homepage
            if (PACKAGE.panel.solr.isValidParty()) {
                $('#mainSidebar').block({ message: waitingMessageSearchPanel, css: {  } });
                $.ajax({
                    type : "POST",
                    url : pURL,
                    data : $('#searchPanelFormId').find('input, select').not('[value=""], [value="-1"],[value="on"]').serialize(),
                    error: function() {
                        $('#mainSidebar').unblock();
                    },
                    success : function(data) {
                        $('#loadRefreshedPanel').html(dataFilter(data));
                        createDatePicker();
                        $('#mainSidebar').unblock();
                    }
                });
            } else {
                element_to_scroll_to = document.getElementById('WarningAnchor');
                element_to_scroll_to.scrollIntoView();
            }
        } else if (autoRefresh == 'true') {
            //In this case is when we have an autorefresh panel for example NECNL, TC with SOLR and FACET
            //we need to set the latest facet selected when the customer has clicked one, otherwise(pagination ,refresh or click the search button) the value is "" and we take in in account to calculate the facet locking previous values
            //Important this input hidden is not present in the home pages panels as the remember facet functionality is only for SRP
            document.getElementById("lastFacetClicked").value = object.name
            PACKAGE.panel.solr.validateParty();
        } else {
            //In this case we are not in an autorefresh panel NECDE for example that has no SORL no Facets
            //I we don't have an autorefresh panel and we change the destination we should hide the region,and set it to default value
            if (object.id=="Destination" && document.getElementById("Region") != null ) {
                document.getElementById("Region").value="-1"
                document.getElementById("RegionContent").style.display="none"
            }else//this awfull code is to fulfill analitics department requirements, they want '1 woche' in case of selecting 1 week in the duration ONLY FOR GERMANY!!!!
            if (object.id=="Duration") {
                $('#durationCattParamsWorkAround').val($('#Duration').find('option:selected').text());
            }
        }
    }
//the message to display in the ajax waiting page
    var waitingMessageSearchPanel = '<div><div style="clear:both;"><img alt="Loading" src="/ota/themes/' + i18n['common.siteid'] + '/img/loadingAjax.gif" style="display:block;margin-left: auto;margin-right: auto;"/></div><div style="clear:both"><h2>' +  i18n['common.pleaseWait'] + '</h2> <h2>' + i18n['common.updatingResults'] + '</h2></div></div>'

    var createDatePicker=function() {

        var searchPanelAmend = document.getElementById('searchPanelAmend').value;
        var departureDate = $("#departureDate");
        var returnDate = $("#returnDate");
        locale = $('#language').val();

        if (locale == 'nl_NL'){
            var _closeText="Gedaan";
            var _prevText="&larr;";
            var _nextText="&rarr;";
            var _currentText="Vandaag";
            var _monthNames= ['januari', 'februari', 'maart', 'april', 'mei', 'juni','juli', 'augustus', 'september', 'oktober', 'november', 'december'];
            var _monthNamesShort=['jan', 'feb', 'maa', 'apr', 'mei', 'jun','jul', 'aug', 'sep', 'okt', 'nov', 'dec'];
            var _dayNames =['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'];
            var _dayNamesShort =['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'];
            var _dayNamesMin= ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'];
            var _weekHeader="Wk";
            var _dateFormat="yy-mm-dd";              
            if(minDate != undefined){
                var _firstDay = minDate;
            }else{
                var _firstDay = 1;
            }
            if(maxDate != undefined){
                var _lastDay = maxDate;
            }else{
                var _lastDay = '+24M';
            }
        } else if (locale == 'de_DE'){
            var _closeText="Erledigt";
            var _prevText="Früher";
            var _nextText="Nächste";
            var _currentText="Heute";
            var _monthNames=['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
            var _monthNamesShort=['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
            var _dayNames=['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'];
            var _dayNamesShort=['So','Mo','Di','Mi','Do','Fr','Sa'];
            var _dayNamesMin=['So','Mo','Di','Mi','Do','Fr','Sa'];
            var _weekHeader="Wk";
            var _dateFormat="yy-mm-dd";
            var _firstDay = 0;
            var _lastDay = '+24M';
        }

        departureDate.datepicker({
            minDate: _firstDay,
            showOn: "both",
            //buttonImage: "images/calendar.gif",
            buttonText: "<i class='mediumIcon-calendar'></i>"+searchPanelAmend+"",
            dateFormat: "yy-mm-dd",
            numberOfMonths: 1,
            closeText: departureDate,
            prevText: _prevText,
            nextText: _nextText,
            currentText: _currentText,
            monthNames: _monthNames,
            monthNamesShort: _monthNamesShort,
            dayNames: _dayNames,
            dayNamesShort: _dayNamesShort,
            dayNamesMin: _dayNamesMin,
            weekHeader: _weekHeader,
            firstDay: _firstDay,
            maxDate: _lastDay,
            dateFormat: _dateFormat,
            changeMonth: true,
            changeYear: true,
            onSelect: function(textoFecha, objDatepicker){
                var selectedDate = $(this).datepicker('getDate');
                var nextDate = new Date(selectedDate.getTime());
                nextDate.setDate(nextDate.getDate() + 1);
                $('#returnDate').datepicker("option", "minDate",  nextDate);
                $("#departureDate").val(textoFecha);
                //if we have to launch a search with the date
                if($("#departureDate").attr("autorefresh")=='true'){
                    updateSearchPanel('true',document.getElementById('departureDate'));
                }
            }
        });
        returnDate.datepicker({
            minDate: 1,
            showOn: "both",
            //buttonImage: "images/calendar.gif",
            buttonText: "<i class='mediumIcon-calendar'></i>"+searchPanelAmend+"",
            dateFormat: "yy-mm-dd",
            numberOfMonths: 1,
            closeText: departureDate,
            prevText: _prevText,
            nextText: _nextText,
            currentText: _currentText,
            monthNames: _monthNames,
            monthNamesShort: _monthNamesShort,
            dayNames: _dayNames,
            dayNamesShort: _dayNamesShort,
            dayNamesMin: _dayNamesMin,
            weekHeader: _weekHeader,
            firstDay: _firstDay,
            dateFormat: _dateFormat,
            changeMonth: true,
            changeYear: true,
            onSelect: function(textoFecha, objDatepicker){
                $("#returnDate").html(textoFecha);
                //if we have to launch a search with the date
                if($("#returnDate").attr("autorefresh")=='true'){
                    updateSearchPanel('true',document.getElementById('returnDate'));
                }
            }
        });
        //configureLocale($('#siteId').val());
    }

    $(document).ready(function() {
        createDatePicker();
        // show depature date popup when icon clicked
        $('#departureDateDiv').find('.ui-datepicker-trigger').click(function() {
            //$('.ui-datepicker-trigger').click(function() {
            $('#departureDate').datepicker('show');
        });
        // show return date popup when icon clicked
        $('#returnDateDiv').find('.ui-datepicker-trigger').click(function() {
            $('#returnDate').datepicker('show');
        });
    });


    /**
     * Function to unlock a selected facet and launch another search with "any" as facet value, only available with autorefresh
     */
    var unlockSelection=function(formInput) {
        if(PACKAGE.panel.solr.isValidParty() == true){
            //we set the input value to -1 that means "any"
            formInput.value=-1
            if ($('#refreshSearchPanel').length > 0) {
                updateSearchPanel('false');
            } else {
                //and we launch the search
                PACKAGE.panel.solr.validateParty();
            }
        }
    }

    /**
     * Function manage the logic of the passengers in the results panel
     */
    var updateSearchPanelRooms=function(totalNumberOfRooms,type){
        var numberOfRooms = document.getElementById("numberOfRooms").value
        if(type=="add"){
            numberOfRooms ++;
        }else{
            numberOfRooms --;
        }
        if((numberOfRooms<=totalNumberOfRooms) && (numberOfRooms>0)){
            for ( var r = 0; r < totalNumberOfRooms; r++) {
                if(r<numberOfRooms){
                    var div = document.getElementById("room" + r);
                    if (div != null) {
                        div.style.display = "block";
                    }
                }else{
                    var div = document.getElementById("room" + r);
                    if (div != null) {
                        div.style.display = "none";
                    }
                }
            }
            document.getElementById("numberOfRooms").value = numberOfRooms;
            if(numberOfRooms==totalNumberOfRooms){
                document.getElementById("addRoomLinkDiv").style.display = "none";
                document.getElementById("deleteRoomLinkDiv").style.display = "block";
            }else{
                if(numberOfRooms==1){
                    document.getElementById("addRoomLinkDiv").style.display = "block";
                    document.getElementById("deleteRoomLinkDiv").style.display = "none";
                }else{
                    document.getElementById("addRoomLinkDiv").style.display = "block";
                    document.getElementById("deleteRoomLinkDiv").style.display = "block";
                }
            }
        }
    }

    var displayChilds=function(totalNumberOfChildren, numberOfChildren, roomNumber) {
        for (var r = 0; r < totalNumberOfChildren; r++) {
            if (r < numberOfChildren) {
                var div = document.getElementById("childAgeR" + roomNumber + "C" + r);
                if (div != null) {
                    div.style.display = "block";
                }
            } else {
                var div = document.getElementById("childAgeR" + roomNumber + "C" + r);
                if (div != null) {
                    div.style.display = "none";
                }
            }
        }
    }

    var updateSearchPanelChildAge=function(totalNumberOfChildren,chosen,roomNumber){
        var numberOfChildren = $('#numChildren'+roomNumber).val();
        displayChilds(totalNumberOfChildren, numberOfChildren, roomNumber);
        if(numberOfChildren!=0){
            $('#editChilds'+roomNumber).removeClass('fade');
            for(var i=0;i<=totalNumberOfChildren;i++){
                $('#childAgeErrorR'+roomNumber).hide();
                $('[id*="childAges' + i + '"]').removeClass('facetInputError');
            }
        }else{
            for(var i=0;i<=roomNumber;i++){
                $('#searchAssistChild'+i).removeClass('in');
            }
            $('#editChilds'+roomNumber).removeClass('in');
            $('#editChilds'+roomNumber).addClass('fade');
        }
    }
	

    return {updateSearchPanel : updateSearchPanel,
        unlockSelection:unlockSelection,
        updateSearchPanelRooms:updateSearchPanelRooms,
        updateSearchPanelChildAge:updateSearchPanelChildAge,
        displayChilds:displayChilds,
        createDatePicker:createDatePicker
        //validateMoreThan9Pax2:validateMoreThan9Pax2,
        //validateChildren2:validateChildren2
    }
}(PACKAGE||{},jQuery));


